import 'package:boss/main.dart';
import 'package:boss/models/store_message.dart';
import 'package:boss/provider/login_user_provider.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:flustars/flustars.dart' as flustars;

class StoreMessageProvider extends ChangeNotifier {
  StoreMessage storeMessage;

  String get storeAddress {
    if (storeMessage == null) {
      return '正在加载...';
    }

    return '${storeMessage.province}-${storeMessage.city}-${storeMessage.district}';
  }

  bool get isShowLoading => storeMessage == null;

  Future<bool> initData() async {
    try {
      if (isShowLoading) showLoadingToast();
      var loginUserProvider = Provider.of<LoginUserProvider>(GlobalPageContext.instance.context, listen: false);
      var response = await api.getStoreMessage(loginUserProvider.loginUser.storeId);

      if (!response.successful()) {
        toast(response.msg);
        return false;
      }

      storeMessage = response.data;
      notifyListeners();

      return true;
    } catch (e) {
      toast(e.toString());
      return false;
    } finally {
      hideLoadingToast();
    }
  }

  updateStoreMessage(StoreMessage message, {bool isPop = true}) async {
    if (!RegUtil.testNotEqEmpty(message.storeName)) {
      toast('请输入店铺名');
      return;
    }

    if (!RegUtil.testNotEqEmpty(message.addressDetail)) {
      toast('请输入详细地址');
      return;
    }

    if (!RegUtil.testNotEqEmpty(message.latitude)) {
      toast('当前店铺地址定位不到,请检查地址');
      return;
    }

    if (!RegUtil.testPhone(message.phone)) {
      toast('请输入正确的手机号码');
      return;
    }

    if (!flustars.TextUtil.isEmpty(message.email) && !RegUtil.testEmail(message.email)) {
      toast('请输入正确的邮箱');
      return;
    }

    try {
      showLoadingToast();
      var response = await api.updateStoreMsg(message);
      if (!response.successful()) {
        toast(response.msg);
        return;
      }

      storeMessage = message;
      notifyListeners();

      var loginUserProvider = Provider.of<LoginUserProvider>(
        GlobalPageContext.instance.context,
        listen: false,
      );
      loginUserProvider.updateStoreName(storeMessage.storeName);

      toast('修改店铺信息成功');

      if (isPop) Navigator.pop(GlobalPageContext.instance.context);
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  updateStoreHeadImage(String url) async {
    storeMessage.storeHeadImage = url;
    await updateStoreMessage(
      storeMessage,
      isPop: false,
    );
  }

  clearData() {
    storeMessage = null;
  }
}
